package com.cskaoyan.service.impl;

import com.cskaoyan.bean.CskaoyanmallCoupon;
import com.cskaoyan.bean.CskaoyanmallCouponExample;
import com.cskaoyan.bean.CskaoyanmallCouponUser;
import com.cskaoyan.bean.CskaoyanmallCouponUserExample;
import com.cskaoyan.bean.bo.ExtensionCouponCreatBo;
import com.cskaoyan.bean.vo.CouponUserVo;
import com.cskaoyan.bean.vo.CouponVo;
import com.cskaoyan.bean.vo.WXCouponListVo;
import com.cskaoyan.bean.vo.WxCouponMyListVo;
import com.cskaoyan.mapper.CskaoyanmallCouponMapper;
import com.cskaoyan.mapper.CskaoyanmallCouponUserMapper;
import com.cskaoyan.service.ExtensionCouponService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ExtensionCouponServiceImpl implements ExtensionCouponService {

    @Autowired
    CskaoyanmallCouponMapper mapper;

    @Autowired
    CskaoyanmallCouponUserMapper mapperUserCoupon;

    /**
     * 添加优惠券
     * @param couponBo
     * @return
     */
    @Override
    public CskaoyanmallCoupon addCoupon(ExtensionCouponCreatBo couponBo) {
        // 有效时间限制，如果是0，则基于领取时间的有效天数days；如果是1，则start_time和end_time是优惠券有效期；
        // 若传入timeType是0，则需要计算出startTime和endTime

        CskaoyanmallCoupon coupon = new CskaoyanmallCoupon();
        coupon.setName(couponBo.getName());
        coupon.setDesc(couponBo.getDesc());
        coupon.setTag(couponBo.getTag());
        coupon.setTotal(Integer.valueOf(couponBo.getTotal()));
        coupon.setDiscount(new BigDecimal(couponBo.getDiscount()));
        coupon.setMin(new BigDecimal(couponBo.getMin()));
        coupon.setLimit(new Short(couponBo.getLimit()));
        coupon.setType(couponBo.getType());
        coupon.setStatus(couponBo.getStatus());
        coupon.setGoodsType(couponBo.getGoodsType());
//        coupon.setGoodsValue(couponBo.getGoodsValue());
        coupon.setTimeType(couponBo.getTimeType());
        coupon.setDays(new Short(couponBo.getDays()));

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (couponBo.getTimeType() == 1) {
            String endTime = couponBo.getEndTime();
            String startTime = couponBo.getStartTime();
            try {
                Date end = sf.parse(endTime);
                Date start = sf.parse(startTime);
                coupon.setStartTime(start);
                coupon.setEndTime(end);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (couponBo.getTimeType() == 0) {
            Date date = new Date();
            Calendar timeStart = Calendar.getInstance();
            timeStart.setTime(date);
            timeStart.set(Calendar.DATE, timeStart.get(Calendar.DATE) + coupon.getDays());
            Date timeEnd = timeStart.getTime();

            coupon.setStartTime(date);
            coupon.setEndTime(timeEnd);
        }

        mapper.insertSelective(coupon);

        return coupon;
    }

    @Override
    public CouponVo vagueQueryCoupons(Integer page, Integer limit, String sort, String order, String name, Short type, Short status) {

        PageHelper.startPage(page, limit);
        CskaoyanmallCouponExample couponExample = new CskaoyanmallCouponExample();
        CskaoyanmallCouponExample.Criteria criteria = couponExample.createCriteria();

        if (name != null && !"".equals(name)){
            criteria.andNameLike("%" + name + "%");
        }

        if (type != null){
            criteria.andTypeEqualTo(type);
        }
        if (status != null){
            criteria.andStatusEqualTo(status);
        }

        List<CskaoyanmallCoupon> coupons = mapper.selectByExample(couponExample);

        Iterator<CskaoyanmallCoupon> iterator = coupons.iterator();

        while (iterator.hasNext()) {
            if (iterator.next().getDeleted()) {
                iterator.remove();
            }
        }

        PageInfo<CskaoyanmallCoupon> pageInfo = new PageInfo<>(coupons);
        long total = pageInfo.getTotal();

        CouponVo couponVo = new CouponVo();
        couponVo.setTotal(total);
        couponVo.setItems(coupons);


        return couponVo;
    }

    /**
     * 编辑优惠券
     */
    @Override
    public CskaoyanmallCoupon updateCoupon(CskaoyanmallCoupon couponUpdateBo) {

        // 有效时间限制，如果是0，则基于领取时间的有效天数days；如果是1，则start_time和end_time是优惠券有效期；
        if (couponUpdateBo.getTimeType() == 0){
            Calendar instance = Calendar.getInstance();
            instance.setTime(couponUpdateBo.getStartTime());
            instance.set(Calendar.DATE, instance.get(Calendar.DATE) + couponUpdateBo.getDays());
            Date endTime = instance.getTime();
            couponUpdateBo.setEndTime(endTime);
        }
        mapper.updateByPrimaryKey(couponUpdateBo);

        return couponUpdateBo;
    }

    @Override
    public Integer delCoupon(CskaoyanmallCoupon couponBo) {

        couponBo.setDeleted(true);
        Integer i = mapper.updateByPrimaryKey(couponBo);

        return i;
    }

    /**
     * 根据优惠券id查询优惠券
     */
    @Override
    public CskaoyanmallCoupon queryCouponById(Integer id) {

        CskaoyanmallCoupon cskaoyanmallCoupon = mapper.selectByPrimaryKey(id);

        return cskaoyanmallCoupon;
    }

    @Override
    public CouponUserVo queryUserByCouponId(Integer page, Integer limit, Integer couponId, String sort, String order, Integer userId, Integer status) {


        PageHelper.startPage(page, limit);
        CskaoyanmallCouponUserExample couponUserExample = new CskaoyanmallCouponUserExample();
        if (!ObjectUtils.isEmpty(sort) && !ObjectUtils.isEmpty(order)) {
            couponUserExample.setOrderByClause(sort + " " + order);
        }
        CskaoyanmallCouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andCouponIdEqualTo(couponId);

        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        if (status != null){
            criteria.andStatusEqualTo((short)status.intValue());
        }

        List<CskaoyanmallCouponUser> cskaoyanmallCouponUsers = mapperUserCoupon.selectByExample(couponUserExample);

        PageInfo<CskaoyanmallCouponUser> couponUserPageInfo = new PageInfo<>(cskaoyanmallCouponUsers);
        long total = couponUserPageInfo.getTotal();

        CouponUserVo couponUserVo = new CouponUserVo();
        couponUserVo.setTotal(total);
        couponUserVo.setItems(cskaoyanmallCouponUsers);

        return couponUserVo;
    }

//    @Override
//    public WxCouponMyListVo wxListCoupon(Integer status, Integer page, Integer size, Integer userId) {
//
////        先根据userId和status查出对应的couponId
//        CskaoyanmallCouponUserExample couponUserExample = new CskaoyanmallCouponUserExample();
//        CskaoyanmallCouponUserExample.Criteria criteria = couponUserExample.createCriteria();
//        criteria.andUserIdEqualTo(userId);
//        criteria.andStatusEqualTo(((short) status.intValue()));
//
//        List<CskaoyanmallCouponUser> couponUsers = mapperUserCoupon.selectByExample(couponUserExample);
//
////        初始化一个数组用来接收couponIds
//        ArrayList<Integer> couponIds = new ArrayList<>();
//
//        Iterator<CskaoyanmallCouponUser> iterator = couponUsers.iterator();
//        int i = 0;
//        while (iterator.hasNext()) {
//            couponIds.add(iterator.next().getCouponId());
//        }
//
////        去优惠券表中查优惠券
//        List<CskaoyanmallCoupon> couponList = new ArrayList<>();
//
//        CskaoyanmallCouponExample cskaoyanmallCouponExample = new CskaoyanmallCouponExample();
//        CskaoyanmallCouponExample.Criteria criteria1 = cskaoyanmallCouponExample.createCriteria();
//        criteria1.andIdIn(couponIds);
//
//        PageHelper.startPage(page, size);
//        List<CskaoyanmallCoupon> coupons = mapper.selectByExample(cskaoyanmallCouponExample);
//        PageInfo<CskaoyanmallCoupon> couponPageInfo = new PageInfo<>(coupons);
//        long total = couponPageInfo.getTotal();
//
//        WxCouponMyListVo wxCouponMyListVo = new WxCouponMyListVo();
//        wxCouponMyListVo.setCount(total);
//        wxCouponMyListVo.setData(coupons);
//
//        return wxCouponMyListVo;
//    }
}
